"""
通过ssh将文件传输至树莓派容器内的指定文件夹

@Author:czy(zhenyuan.chen@stu.xjtu.edu.cn)
@Date:2025/10/10
@Version:v1.1.1
"""

import paramiko
import os
from datetime import datetime

def transfer_file(local_file, container_name, target_path,
                               remote_user="pi", remote_host="10.10.10.2",
                               password=None):
    try:
        # 创建SSH客户端
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        print("正在连接到树莓派...")
        # 使用密码连接
        ssh.connect(remote_host, username=remote_user, password=password)

        # 读取文件内容
        print(f"读取本地文件: {local_file}")
        with open(local_file, 'rb') as f:
            file_content = f.read()

        # 构建容器内目标路径
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

        filename = os.path.basename(local_file)

        # 分离文件名和扩展名
        name, ext = os.path.splitext(filename)

        # 拼接新的文件名（包含时间戳）
        new_filename = f"{name}_{timestamp}{ext}"

        # 拼接完整路径
        container_full_path = os.path.join(target_path, new_filename)

        # 执行docker命令传输文件
        command = f"docker exec -i {container_name} tee {container_full_path} > /dev/null"
        print(f"执行命令: {command}")

        stdin, stdout, stderr = ssh.exec_command(command)
        stdin.write(file_content)
        stdin.flush()
        stdin.channel.shutdown_write()

        # 检查执行状态
        exit_status = stdout.channel.recv_exit_status()

        if exit_status == 0:
            print(f"✓ 文件成功传输到容器: {container_name}:{container_full_path}")
        else:
            error = stderr.read().decode()
            print(f"✗ 传输失败: {error}")

        ssh.close()

    except Exception as e:
        print(f"错误: {str(e)}")

if __name__ == "__main__":
    local_file = r"SensorData\sensor_data_demo.json"
    container_name = "jupyterlab"
    target_path = "/root/test01/"
    password = "000000"
    remote_host = "10.10.10.2"

    transfer_file(
        local_file=local_file,
        container_name=container_name,
        target_path=target_path,
        remote_host=remote_host,
        password=password
    )